package com.dsk.connector.config;

import cn.sanenen.sunutils.queue.SMQ;
import com.dsk.connector.commons.function.SimpleFunction;
import io.debezium.engine.DebeziumEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;

@Component
public class CloseApplication implements DisposableBean {
    Logger logger= LoggerFactory.getLogger(CloseApplication.class);
// 为了实现条件依赖，暂不使用 注解注入
//    @Qualifier("debeziumExecutor")
    private ExecutorService debeziumExecutor;
    // 为了实现条件依赖，暂不使用 注解注入
//    @Qualifier("sinkExecutor")
    private ExecutorService sinkExecutor;
    // 为了实现条件依赖，暂不使用 注解注入
//    @Autowired(required = false)
    private DebeziumEngine debeziumEngine;

    public ExecutorService getDebeziumExecutor() {
        return debeziumExecutor;
    }

    public void setDebeziumExecutor(ExecutorService debeziumExecutor) {
        this.debeziumExecutor = debeziumExecutor;
    }

    public ExecutorService getSinkExecutor() {
        return sinkExecutor;
    }

    public void setSinkExecutor(ExecutorService sinkExecutor) {
        this.sinkExecutor = sinkExecutor;
    }


    public DebeziumEngine getDebeziumEngine() {
        return debeziumEngine;
    }

    public void setDebeziumEngine(DebeziumEngine debeziumEngine) {
        this.debeziumEngine = debeziumEngine;
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("Closing Debezium Engine");
        logger.info("Closing Debezium Engine");
        //关闭消息队列，把内存中的数据放入到文件中，防止数据丢失
        this.saveClose("Closed SMQ",()->{
            SMQ.close();
        });
        //关闭Debezium引擎
        this.saveClose("Closed DebeziumEngine",()->{
            if(this.debeziumEngine!=null){
                this.debeziumEngine.close();
            }
        });

        this.saveClose("Closed DebeziumExecutor",()->{
            if(this.debeziumExecutor!=null){
                this.debeziumExecutor.shutdown();
            }
        });

        this.saveClose("Closed SinkExecutor",()->{
            if(this.sinkExecutor!=null){
                this.sinkExecutor.shutdown();
            }
        });

        System.out.println("Close finished");

    }

    private void saveClose(String msg,SimpleFunction function){
        try{
            function.execute();
            System.out.println(msg);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }


}
